#include <brpc/server.h>
#include <butil/logging.h>
#include <iostream>
#include "main.pb.h"

// 1. 继承于 EchoService 创建一个子类，并实现 rpc 调用的业务功能
class EchoServiceImpl : public example::EchoService {
public:
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}

    virtual void Echo(google::protobuf::RpcController* controller, const ::example::EchoRequest* request,
                    example::EchoResponse* response, google::protobuf::Closure* done) override
    {
        brpc::ClosureGuard rpc_guard(done);
        std::cout << "收到消息:" << request->message() << std::endl;

        std::string str = request->message() + "--这是响应!!";
        response->set_message(str);

        // rpc_guard 自动调用 run 接口  done->Run();
    }
}; 

int main()  
{ 
    // 关闭 brpc 的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    // 2. 构造服务器对象
    brpc::Server server;

    // 3. 向服务器对象中，新增 EchoService 服务的子类
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);    // 失败不销毁 
    if (ret == -1) {
        std::cout << "添加 rpc 服务失败! \n";
        return -1;
    }

    // 4. 启动服务器 
    brpc::ServerOptions options;
    options.idle_timeout_sec = -1;      // 连接超时销毁
    options.num_threads = 4;            // io线程数
    ret = server.Start(8080, &options);
    if (ret == -1) {
        std::cout << "启动服务器失败! \n";
        return -1;
    }

    server.RunUntilAskedToQuit();

    return 0;
}